package com.ajx.core.net.rest;

import android.text.TextUtils;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class CubeRest {

    private final String ip;
    private final long readTime;
    private final long connectTime;
    private final List<Interceptor> interceptors;

    CubeRest(String ip, long readTime, long connectTime, List<Interceptor> interceptors) {
        this.ip = ip;
        this.readTime = readTime;
        this.connectTime = connectTime;
        this.interceptors = interceptors;
    }


    public <T> T create(Class<T> service) {
        if (TextUtils.isEmpty(ip)){
            throw new RuntimeException("没有配置默认的host ip,请配置默认ip或传入有效ip(不为空)");
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ip)
                .client(getOKHttpClient(readTime, connectTime, interceptors))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(service);
    }

    private OkHttpClient getOKHttpClient(long readTime, long connectTime, List<Interceptor> interceptors) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(connectTime <= 0 ? 20 : connectTime, TimeUnit.SECONDS)
                .readTimeout(readTime <= 0 ? 20 : readTime, TimeUnit.SECONDS);

        if (interceptors != null && !interceptors.isEmpty()) {
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
        }
        return builder.build();
    }

    public static CubeRestBuilder builder() {
        return new CubeRestBuilder();
    }




    public  <T> T getService(Class<T> service) {
        return create(service);
    }

    public static <T> void toSubscribe(Observable<T> o, Observer<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }


}
